package com.siyoumi.sh.modules.ccb;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.siyoumi.sh.component.XRedis;
import com.siyoumi.sh.modules.ccb.entity.*;
import com.siyoumi.sh.modules.common.IHandle;
import com.siyoumi.sh.modules.common.send_msg.TlSendMsg;
import com.siyoumi.util.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//建行ccb,任务
@Slf4j
public class CcbTaskHandle
        extends CcbHandleBase
        implements IHandle {


    @SneakyThrows
    @Override
    public void run() {
        TlSendMsg.remove();

        List<CcbApiToken> tokenArr = getArrToken();
        if (tokenArr.size() <= 0) {
            log.error("未配置CCB_TOKEN");
            return;
        }
        log.info("BEGIN: {}", XDate.toDateTimeString());

        logAndSet(TlSendMsg.get(), "**留学萌新专享礼** \n\n");
        for (CcbApiToken apiToken : getArrToken()) {
            nf(apiToken);
            sendMsg(TlSendMsg.get().toString());
        }
        TlSendMsg.remove();
        log.info("END: {}", XDate.toDateTimeString());
    }

    String actCode = "AP010202310271084871";

    //留学萌新专享礼
    private void nf(CcbApiToken apiToken) {
        CcbFuUser user = getUserInfo(apiToken);
        log.info("user_info {}", XJson.toJSONString(user));
        if (user == null) {
            return;
        }

        sleepAndLog(1);
        List<CcbFuTask> taskList = getTaskList(user);
        if (taskList == null) {
            return;
        }
        for (CcbFuTask task : taskList) {
            if (task.getStatus() == 0) {
                logAndSet(TlSendMsg.get(), "浏览任务" + task.getTitle() + "\n\n");
                //领取任务
                getTaskGet(user, task.getTaskId());
                sleepAndLog(2);
            }
        }

        //抽奖
        for (CcbFuTask task : taskList) {
            XReturn rChou = chou(user);
            if (rChou.err()) {
                break;
            } else {
                logAndSet(TlSendMsg.get(), rChou.getErrMsg() + "\n\n");
            }
            sleepAndLog(1);
        }
    }

    /**
     * 领取任务
     *
     * @param taskId
     */
    private XReturn getTaskGet(CcbFuUser user, String taskId) {
        String url = "https://event.ccbft.com/api/activity/nf/largeTurntableOverseas/toReach";

        Map<String, String> mapHeader = getHeader();
        mapHeader.put("secParam", user.getToken());

        Map<String, Object> postData = new HashMap<>();
        postData.put("activityCode", actCode);
        postData.put("userId", user.getUserId());
        postData.put("taskId", taskId);

        return postJson(url, mapHeader, postData);
    }

    /**
     * 任务列表
     */
    private List<CcbFuTask> getTaskList(CcbFuUser user) {
        String url = "https://event.ccbft.com/api/activity/nf/largeTurntableOverseas/getActivityTaskList";

        Map<String, String> mapHeader = getHeader();
        mapHeader.put("secParam", user.getToken());

        Map<String, Object> postData = new HashMap<>();
        postData.put("activityCode", actCode);
        postData.put("userId", user.getUserId());

        XReturn r = postJson(url, mapHeader, postData);
        if (r.err()) {
            logAndSet(TlSendMsg.get(), "获取任务列表失败：" + r.getErrMsg() + "\n\n");
            return null;
        }

        String listJson = XJson.toJSONString(r.getData("data"));
        List<CcbFuTask> list = XJson.parseArray(listJson, CcbFuTask.class);

        return list;
    }

    /**
     * 抽奖
     */
    private XReturn chou(CcbFuUser user) {
        String url = "https://event.ccbft.com/api/activity/nf/largeTurntableOverseas/activityParticipation";

        Map<String, String> mapHeader = getHeader();
        mapHeader.put("secParam", user.getToken());

        Map<String, Object> postData = new HashMap<>();
        postData.put("activityCode", actCode);
        postData.put("userId", user.getUserId());

        return postJson(url, mapHeader, postData);
    }


    /**
     * 获取token和userId
     */
    @SneakyThrows
    private CcbFuUser getUserInfo(CcbApiToken apiToken) {
        String key = "user_info|" + apiToken.getUuid();
        String redisJson = XRedis.getBean().get(key);
        if (XStr.hasAnyText(redisJson)) {
            return JSON.parseObject(redisJson, CcbFuUser.class);
        }

        CcbUser user = getZhcToken(apiToken, "pFHdDPa5_OrZYwp3AJlPTA");
        if (user == null) {
            return null;
        }

        sleepAndLog(1);
        String url = "https://event.ccbft.com/api/activity/nf/largeTurntableOverseas/userInfo";

        Map<String, Object> postData = new HashMap<>();
        postData.put("activityCode", actCode);
        postData.put("token", user.getZhcToken());

        log.debug("url: {}", url);
        log.debug("post_data: {}", XJson.toJSONString(postData));

        XHttpClient client = XHttpClient.getInstance();
        CloseableHttpResponse response = client.postReturnObj(url, null, postData);
        String returnStr = EntityUtils.toString(response.getEntity());
        log.debug("return_str: {}", returnStr);

        XReturn r = paresR(returnStr);
        if (r.err()) {
            logAndSet(TlSendMsg.get(), "获取用户信息失败：" + r.getErrMsg() + "\n\n");
            return null;
        }

        JSONObject data = r.getData("data");

        String secParam = response.getFirstHeader("secParam").getValue();

        CcbFuUser fuUser = new CcbFuUser();
        fuUser.setUserId(data.getString("userId"));
        fuUser.setToken(secParam);

        XRedis.getBean().setEx(key, XJson.toJSONString(fuUser), 60 * 5);

        return fuUser;
    }
}
